﻿//======================================================
//==     (c)2013  OpenLayers.cn inc by 飞龙在天 v1.0  ==
//==          Forum:bbs.OpenLayers.cn                 ==
//==         Website:www.OpenLayers.cn                ==
//== 开源旗舰版见 淘宝: http://giscenter.taobao.com   ==
//======================================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Common;
using System.Threading;

namespace OLOffLineMap
{
    public partial class MainForm : Form
    {
        private string saveTilePathStr = "";
        private string MapTypeStr = "";
        public ArrayList downData = new ArrayList();
        private Thread m_Thread;
        double XMin = 0.0;
        double YMin = 0.0;
        double XMax = 0.0;
        double YMax = 0.0;
        int currentTile = 0;
        Int64 taskTileSum = 0;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                //加载地图
                string address = "File:\\" + Application.StartupPath + "\\index.htm";
                Uri url = new Uri(address);
                webBrowser1.Url = url;
                webBrowser1.ScriptErrorsSuppressed = false;
                电子地图ToolStripMenuItem.Checked = true;
                for (int i = 0; i < 22; i++)
                {
                    ListViewItem item = new ListViewItem(i.ToString());
                    this.zoomList.Items.Add(item);

                }
                MapTypeStr = "GOOGLE_ROADMAP";
                this.Icon = new Icon("GmapDownload.ico");
                this.toolStripProgressBar1.Visible = false;
                this.suspend.Enabled = false;
                this.Stop.Enabled = false;
            }
            catch (Exception except)
            {
                MessageBox.Show(except.Message, "提示！", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void 电子地图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
                mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
                电子地图ToolStripMenuItem.Checked = true;
                卫星地图ToolStripMenuItem.Checked = false;
                地形地图ToolStripMenuItem.Checked = false;
                MapTypeStr = "GOOGLE_ROADMAP";
                win.execScript("SetRoadMap()", "javascript");
            }
            else
            {
                MessageBox.Show("地图没有加载完，请稍后操作！！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
        }

        private void 卫星地图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
                mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
                电子地图ToolStripMenuItem.Checked = false;
                卫星地图ToolStripMenuItem.Checked = true;
                地形地图ToolStripMenuItem.Checked = false;
                MapTypeStr = "GOOGLE_SATELLITE";
                win.execScript("SetSatelliteMap()", "javascript");
            }
            else
            {
                MessageBox.Show("地图没有加载完，请稍后操作！！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
        }

        private void 地形地图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
                mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
                电子地图ToolStripMenuItem.Checked = false;
                卫星地图ToolStripMenuItem.Checked = false;
                地形地图ToolStripMenuItem.Checked = true;
                MapTypeStr = "GOOGLE_TERRAIN";
                win.execScript("SetTerrainMap()", "javascript");
            }
            else
            {
                MessageBox.Show("地图没有加载完，请稍后操作！！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            currentXYStatusLabel.Text = "当前坐标：" + this.webBrowser1.Document.GetElementById("mouselongitude").GetAttribute("value");
            zoomclassStatusLabel.Text = "缩放等级：" + this.webBrowser1.Document.GetElementById("ZoomClass").GetAttribute("value");
            txtBounds.Text = this.webBrowser1.Document.GetElementById("BoundsInfo").GetAttribute("value");



        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            this.timer1.Enabled = true;
        }

        private void setTilePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog savetile = new FolderBrowserDialog();
            DialogResult OpenResult = savetile.ShowDialog();
            if (OpenResult != DialogResult.OK)
                return;
            this.saveTilePath.Text = savetile.SelectedPath;
            this.saveTilePathStr = savetile.SelectedPath;

        }

        private void startDl_Click(object sender, EventArgs e)
        {
            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                if (this.MapTypeStr == "")
                {
                    MessageBox.Show("请先选择地图下载类型！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                if (this.txtBounds.Text == "")
                {
                    MessageBox.Show("请先填写地图下载范围！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                if (this.saveTilePath.Text == "")
                {
                    MessageBox.Show("请选择地图瓦片保存路径！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                if (this.zoomList.CheckedItems.Count == 0)
                {
                    MessageBox.Show("请先选择需要下载地图的等级", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }

                ProjectManage pm = new ProjectManage();
                XY minxy1 = new XY();
                XY maxxy1 = new XY();
                minxy1 = pm.LatLonToMercator(XMin, YMin);
                maxxy1 = pm.LatLonToMercator(XMax, YMax);
                GlobalMercator mercator = new GlobalMercator(256);

                XY minxy2 = new XY();
                XY maxxy2 = new XY();
                foreach (ListViewItem item in this.zoomList.CheckedItems)
                {
                    int zoomi = int.Parse(item.Text);
                    minxy2 = mercator.MetersToTile(minxy1.X, minxy1.Y, zoomi);
                    maxxy2 = mercator.MetersToTile(maxxy1.X, maxxy1.Y, zoomi);
                    string str = zoomi + "," + minxy2.X + "," + maxxy2.X + "," + minxy2.Y + "," + maxxy2.Y + "," + MapTypeStr;
                    this.downData.Add(str);

                    Bounds b = new Bounds(minxy2.X, minxy2.Y, maxxy2.X, maxxy2.Y);
                    taskTileSum += GettileSum(b, zoomi);
                }
                this.startDl.Enabled = false;
                this.m_Thread = new Thread(new ThreadStart(this.ThreadWork));
                m_Thread.IsBackground = true;
                this.m_Thread.Start();
                toolStripProgressBar1.Minimum = 0;
                toolStripProgressBar1.Maximum =100;
                this.toolStripProgressBar1.Visible = true;
            }
            else
            {
                MessageBox.Show("地图没有加载完，请稍后操作！！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }


        }
        private void ThreadWork()
        {
            for (int i = 0; i < this.downData.Count; i++)
            {
                string[] strArray = this.downData[i].ToString().Split(new char[] { ',' });
                 int zoom = int.Parse(strArray[0]);
                 Int64 minCol = int.Parse(strArray[1]);
                 Int64 minRow = int.Parse(strArray[3]);
                 Int64 maxCol = int.Parse(strArray[2]);
                 Int64 maxRow = int.Parse(strArray[4]);
                string mapType = strArray[5];
                for (Int64 col = minCol; col <= maxCol; col++)
                {

                    for (Int64 row = minRow; row <= maxRow; row++)
                    {

                        Int64 tmsrow = (Int64)Math.Pow(2, zoom) - (row + 1);
                        string filename = saveTilePathStr + "\\" + zoom + "\\" + col + "\\" + tmsrow;
                        string url = TileServer.getTileUrl(mapType, zoom, col, tmsrow);
                        SaveImg.SavePhotoFromUrl(filename, url);
                        this.currentTile++;                     
                        SetLableText(string.Format("完成比例:{0}%", (Convert.ToDecimal(currentTile) / Convert.ToDecimal(taskTileSum) * 100).ToString("f0")));
                        SetPbValue(int.Parse((Convert.ToDecimal(currentTile) / Convert.ToDecimal(taskTileSum) * 100).ToString("f0")));

                    }
                }
 

            }
            this.BeginInvoke(new MethodInvoker(delegate()
                {
                    this.startDl.Enabled = true;
                    taskTileSum = 0;
                    this.toolStripProgressBar1.Visible = false;
                    this.currentTile = 0;
                    this.downData.Clear();
                    MessageBox.Show("地图瓦片下载完成！！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }));

        }

        delegate void labDelegate(string str);
        private void SetLableText(string str)
        {
            if (InvokeRequired)
            {
                Invoke(new labDelegate(SetLableText), new string[] { str });
            }
            else
            {
                labMessage.Text = str;
            }
        }

        delegate void pbDelegate(int value);
        private void SetPbValue(int value)
        {
            if (InvokeRequired)
            {
                Invoke(new pbDelegate(SetPbValue), new object[] { value });
            }
            else
            {
                toolStripProgressBar1.Value = value;
            }
        }

        private void zoomList_ItemChecked(object sender, ItemCheckedEventArgs e)
        {

            Int64 tilesum = 0;
            if (txtBounds.Text != "")
            {
                foreach (ListViewItem item in this.zoomList.CheckedItems)
                {

                    XMin = Convert.ToDouble(txtBounds.Text.Split(';')[0]);
                    YMin = Convert.ToDouble(txtBounds.Text.Split(';')[1]);
                    XMax = Convert.ToDouble(txtBounds.Text.Split(';')[2]);
                    YMax = Convert.ToDouble(txtBounds.Text.Split(';')[3]);
                    int zoomi = int.Parse(item.Text);
                    Bounds b = new Bounds(XMin, YMin, XMax, YMax);
                    tilesum += GettileSum(b, zoomi);

                }

            }
            this.tileSumLabel.Text = "瓦片总数为：" + tilesum.ToString();
        }

        private Int64 GettileSum(Bounds bounds, int zoom)
        {
            Int64 sum = 0;
            ProjectManage pm = new ProjectManage();
            XY minxy1 = new XY();
            XY maxxy1 = new XY();
            minxy1 = pm.LatLonToMercator(XMin, YMin);
            maxxy1 = pm.LatLonToMercator(XMax, YMax);
            GlobalMercator mercator = new GlobalMercator(256);
            XY minxy2 = new XY();
            XY maxxy2 = new XY();
            minxy2 = mercator.MetersToTile(minxy1.X, minxy1.Y, zoom);
            maxxy2 = mercator.MetersToTile(maxxy1.X, maxxy1.Y, zoom);
            sum = Convert.ToInt64((maxxy2.X - minxy2.X + 1) * (maxxy2.Y - minxy2.Y + 1));
            return sum;
        }

        private void txtBounds_TextChanged(object sender, EventArgs e)
        {
            Int64 tilesum = 0;
            if (txtBounds.Text != "")
            {
                foreach (ListViewItem item in this.zoomList.CheckedItems)
                {

                    XMin = Convert.ToDouble(txtBounds.Text.Split(';')[0]);
                    YMin = Convert.ToDouble(txtBounds.Text.Split(';')[1]);
                    XMax = Convert.ToDouble(txtBounds.Text.Split(';')[2]);
                    YMax = Convert.ToDouble(txtBounds.Text.Split(';')[3]);
                    int zoomi = int.Parse(item.Text);
                    Bounds b = new Bounds(XMin, YMin, XMax, YMax);
                    tilesum += GettileSum(b, zoomi);

                }

            }
            this.tileSumLabel.Text = "瓦片总数为：" + tilesum.ToString();
        }

        private void Stop_Click(object sender, EventArgs e)
        {
           
        }

        private void 显示瓦片网格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (webBrowser1.ReadyState == WebBrowserReadyState.Complete)
            {
                mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowser1.Document.DomDocument;
                mshtml.IHTMLWindow2 win = (mshtml.IHTMLWindow2)currentDoc.parentWindow;
                if (!this.显示瓦片网格ToolStripMenuItem.Checked)
                {
                    win.execScript("ShowTileGrid(true)", "javascript");
                    this.显示瓦片网格ToolStripMenuItem.Checked = true;
                }
                else
                {
                    win.execScript("ShowTileGrid(false)", "javascript");
                    this.显示瓦片网格ToolStripMenuItem.Checked = false;
                }
            }
            else
            {
                MessageBox.Show("地图没有加载完，请稍后操作！！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                return;
            }

        }

        private void suspend_Click(object sender, EventArgs e)
        {
            
        }

        private void 关于本软件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About ab = new About();
            ab.Show();
        }



    }
}
